iT邦幫忙

2024 iThome 鐵人賽

DAY 3
0
JavaScript

Javascript網頁程式管理系統系列 第 3

day3 Javascript網頁程式管理公路車倉儲系統

  • 分享至 

  • xImage
  •  

今天是第三天我們可以寫一個javascript網頁程式管理公路車倉儲系統,以下是程式碼
當然可以!這是一個簡單的公路車倉儲系統的網頁應用程式範例,使用了HTML、CSS和JavaScript來實現。此系統允許用戶查看、添加、編輯和刪除倉儲中的公路車。

1. index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>公路車倉儲系統</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>公路車倉儲系統</h1>
    <div id="app">
        <h2>倉儲中的公路車</h2>
        <ul id="bike-list"></ul>
        
        <h2>添加新公路車</h2>
        <form id="bike-form">
            <label for="bike-name">車型名稱:</label>
            <input type="text" id="bike-name" required>
            <label for="bike-brand">品牌:</label>
            <input type="text" id="bike-brand" required>
            <label for="bike-year">年份:</label>
            <input type="number" id="bike-year" required>
            <button type="submit">添加公路車</button>
        </form>
    </div>
    
    <script src="app.js"></script>
</body>
</html>

2. style.css

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

#app {
    background-color: #fff;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    width: 300px;
}

h1, h2 {
    text-align: center;
}

form {
    display: flex;
    flex-direction: column;
}

label, input, button {
    margin-bottom: 10px;
}

button {
    background-color: #007bff;
    color: white;
    border: none;
    padding: 10px;
    cursor: pointer;
    border-radius: 5px;
}

button:hover {
    background-color: #0056b3;
}

3. app.js

document.addEventListener('DOMContentLoaded', () => {
    const bikeList = document.getElementById('bike-list');
    const bikeForm = document.getElementById('bike-form');

    let bikes = [];

    function renderBikes() {
        bikeList.innerHTML = '';
        bikes.forEach((bike, index) => {
            const li = document.createElement('li');
            li.textContent = `${bike.name} (${bike.brand} - ${bike.year})`;
            const editButton = document.createElement('button');
            editButton.textContent = '編輯';
            editButton.onclick = () => editBike(index);
            const deleteButton = document.createElement('button');
            deleteButton.textContent = '刪除';
            deleteButton.onclick = () => deleteBike(index);
            li.appendChild(editButton);
            li.appendChild(deleteButton);
            bikeList.appendChild(li);
        });
    }

    function addBike(name, brand, year) {
        bikes.push({ name, brand, year });
        renderBikes();
    }

    function editBike(index) {
        const bike = bikes[index];
        const newName = prompt('修改車型名稱:', bike.name);
        const newBrand = prompt('修改品牌:', bike.brand);
        const newYear = prompt('修改年份:', bike.year);
        if (newName && newBrand && newYear) {
            bikes[index] = { name: newName, brand: newBrand, year: newYear };
            renderBikes();
        }
    }

    function deleteBike(index) {
        bikes.splice(index, 1);
        renderBikes();
    }

    bikeForm.addEventListener('submit', (event) => {
        event.preventDefault();
        const name = document.getElementById('bike-name').value;
        const brand = document.getElementById('bike-brand').value;
        const year = document.getElementById('bike-year').value;
        addBike(name, brand, year);
        bikeForm.reset();
    });

    renderBikes();
});

說明:

  1. index.html: 此檔案包含了網頁的結構,使用表單讓用戶可以添加公路車,並顯示已添加的公路車列表。

  2. style.css: 此檔案提供了簡單的樣式,使得網頁更加美觀。

  3. app.js: 此檔案包含了JavaScript邏輯,用於處理公路車的添加、編輯和刪除功能。

我下面會以javascript來做解釋
當然可以!讓我們來深入解析這個JavaScript程式的各個部分。

1. 初始化與事件監聽

document.addEventListener('DOMContentLoaded', () => {

這行程式碼使用了 DOMContentLoaded 事件,這個事件會在HTML文件完全加載和解析完成後觸發,而不必等待圖片或樣式表等外部資源。這樣可以確保當我們操作DOM(文檔物件模型)時,網頁結構已經準備好。

2. 元素選取

    const bikeList = document.getElementById('bike-list');
    const bikeForm = document.getElementById('bike-form');

我們使用 document.getElementById() 方法來選取HTML元素。這裡,我們選取了顯示公路車列表的 <ul> 元素 (bikeList) 和用於添加新公路車的 <form> 元素 (bikeForm)。

3. 資料結構

    let bikes = [];

我們定義了一個空陣列 bikes 來儲存所有的公路車資料。每個公路車都是一個物件,包含 name(車型名稱)、brand(品牌)和 year(年份)這三個屬性。

4. 渲染公路車列表

    function renderBikes() {
        bikeList.innerHTML = '';
        bikes.forEach((bike, index) => {
            const li = document.createElement('li');
            li.textContent = `${bike.name} (${bike.brand} - ${bike.year})`;
            const editButton = document.createElement('button');
            editButton.textContent = '編輯';
            editButton.onclick = () => editBike(index);
            const deleteButton = document.createElement('button');
            deleteButton.textContent = '刪除';
            deleteButton.onclick = () => deleteBike(index);
            li.appendChild(editButton);
            li.appendChild(deleteButton);
            bikeList.appendChild(li);
        });
    }

這個函式 renderBikes() 的作用是將 bikes 陣列中的所有公路車渲染到網頁上。

  1. 清空列表:每次渲染前,首先將 bikeList.innerHTML 設為空,確保列表不會重複顯示已經存在的項目。

  2. 遍歷陣列:使用 forEach 方法遍歷 bikes 陣列,對於每一個公路車,建立一個新的 <li> 元素,並將該公路車的資訊顯示出來。

  3. 添加按鈕:為每個 <li> 元素添加兩個按鈕,一個是 editButton 用於編輯,另一個是 deleteButton 用於刪除。這些按鈕的 onclick 事件會觸發對應的編輯或刪除功能。

  4. 顯示列表:將 <li> 元素(包含按鈕)添加到 bikeList 中。

5. 添加新公路車

    function addBike(name, brand, year) {
        bikes.push({ name, brand, year });
        renderBikes();
    }

addBike() 函式負責向 bikes 陣列中添加一個新公路車物件,然後重新渲染列表以顯示更新後的資料。

6. 編輯與刪除功能

    function editBike(index) {
        const bike = bikes[index];
        const newName = prompt('修改車型名稱:', bike.name);
        const newBrand = prompt('修改品牌:', bike.brand);
        const newYear = prompt('修改年份:', bike.year);
        if (newName && newBrand && newYear) {
            bikes[index] = { name: newName, brand: newBrand, year: newYear };
            renderBikes();
        }
    }

    function deleteBike(index) {
        bikes.splice(index, 1);
        renderBikes();
    }
  1. 編輯公路車editBike() 函式使用 prompt() 函式彈出對話框,讓用戶輸入新的車型名稱、品牌和年份。輸入完成後,更新 bikes 陣列中的對應項目,並重新渲染列表。

  2. 刪除公路車deleteBike() 函式使用 splice() 方法從 bikes 陣列中刪除指定的公路車,然後重新渲染列表。

7. 表單提交

    bikeForm.addEventListener('submit', (event) => {
        event.preventDefault();
        const name = document.getElementById('bike-name').value;
        const brand = document.getElementById('bike-brand').value;
        const year = document.getElementById('bike-year').value;
        addBike(name, brand, year);
        bikeForm.reset();
    });

這段程式碼為表單的 submit 事件添加了一個監聽器:

  1. 阻止默認行為event.preventDefault() 防止表單的默認提交行為(這通常會導致頁面重新加載)。

  2. 獲取表單數據:通過表單元素的 value 屬性獲取用戶輸入的車型名稱、品牌和年份。

  3. 添加公路車:調用 addBike() 函式將新公路車添加到列表中。

  4. 重置表單bikeForm.reset() 清空表單欄位,讓用戶可以方便地輸入下一個公路車。

8. 初始化渲染

    renderBikes();

最後,初次加載頁面時,執行 renderBikes() 以確保在頁面上顯示當前的公路車列表(即使最初列表是空的)。

這個JavaScript程式是一個簡單的CRUD(Create, Read, Update, Delete)應用範例,用戶可以在網頁上管理公路車的資料。你可以基於這個基礎進行擴展,例如加入數據持久化(例如使用localStorage),或增強使用者體驗。


上一篇
day 2 Javascript網頁程式管理系統介紹
下一篇
day 4 Javascript網頁程式管理線上購物系統
系列文
Javascript網頁程式管理系統25
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言